package learnjava.concur.chapter4;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 用ReentrantLock实现循环打印
 */

public class P082 {

    static ReentrantLock lock = new ReentrantLock();
    static Condition a = lock.newCondition();
    static Condition b = lock.newCondition();
    static Condition c = lock.newCondition();

    public static void main(String[] args) {
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                try {
                    lock.lock();
                    a.await();
                    System.out.print("a");
                    b.signal();
                }catch (Exception e){

                }finally {
                    lock.unlock();
                }
            }
        }).start();
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000); //如果a.signal时b还没进入await，就会出现问题
                    lock.lock();
                    b.await();
                    System.out.print("b");
                    c.signal();
                }catch (Exception e){

                }finally {
                    lock.unlock();
                }
            }
        }).start();
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                try {
                    lock.lock();
                    c.await();
                    System.out.print("c");
                    a.signal();
                }catch (Exception e){

                }finally {
                    lock.unlock();
                }
            }
        }).start();

        try{
            lock.lock();
            a.signal();
        }finally {
            lock.unlock();
        }
    }

}
